package Thread.Thread03;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private double money;//余额
    private String cardId;//卡号
    //创建了一个锁对象
    private final Lock lk = new ReentrantLock();

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public Account(double money, String cardId) {
        this.money = money;
        this.cardId = cardId;
    }

    public synchronized void drawMoney(double money){
        //先搞清楚是谁来取
        String name = Thread.currentThread().getName();
        lk.lock();//加锁

        //1、判断余额是否足够
        // this正好代表共享资源
        try {
            synchronized (this) {
                if (this.money>=money){
                    System.out.println(name+"来取钱"+money+"成功！");
                    this.money-=money;
                    System.out.println(name+"来取钱后，余额剩余"+this.money+"元！");
                }else {
                    System.out.println(name+"来取钱，余额不足··");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //即使中间出现了bug也能保证及时解锁不会死锁
            lk.unlock();//解锁
        }

    }

    public Account() {
    }
}
